//
//  SISSEscrowAccountApplyViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/10/25.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSEscrowAccountApplyViewController.h"
#import "SISSEscrowAccountApplyViewModel.h"
#import "SISSEscrowAccountShowViewController.h"
#import "SISSHouseProgressModel.h"
#import "SISSHouseProgressRecordInfoModel.h"
#import "SISSPassengerProgressModel.h"
#import "SISSPassengerProgressRecordInfoModel.h"
#import "SISSNetworkingManager+HouseProgress.h"
#import "SISSNetworkingManager+PassengerProgress.h"
#import "SISSPassengerProgressRecordInfoModel.h"
#import "SISSBuyerInfoModel.h"

@interface SISSEscrowAccountApplyViewController ()

/// 保存按钮
@property (weak, nonatomic) UIButton *saveButton;

@property (strong, nonatomic) SISSEscrowAccountApplyViewModel *escrowAccountApplyViewModel;
@property (copy, nonatomic) void(^complete)();

@end

@implementation SISSEscrowAccountApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"资金监管帐户申请";
    
    [self requestSellerAndBuyerInfo];
}

- (void)requestSellerAndBuyerInfo {
    WeakSelf
    __block NSInteger requestCount = 0;
    NSString *ahbpId = self.houseProgressModel ? self.houseProgressModel.ahbpId : self.passengerProgressRecordInfoModel.ahbpId;
    NSInteger houseType = self.houseProgressModel ? self.houseProgressModel.houseresType : self.passengerProgressRecordInfoModel.house_type;
    [kNetworkManager requestProgressSellerInfoWithAhbpId:ahbpId houseType:houseType success:^(SISSSellerInfoModel *sellerInfoModel) {
        self.escrowAccountApplyViewModel.dataArr[0][0].rightStr = sellerInfoModel.seller_name ? sellerInfoModel.seller_name : @" ";
        self.escrowAccountApplyViewModel.dataArr[0][1].rightStr = sellerInfoModel.idNo ? sellerInfoModel.idNo : @" ";
        requestCount++;
        if (self.complete) {
            self.complete();
        }
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    NSString *adbpId = self.houseProgressModel ? self.houseProgressRecordInfoModel.adbpId : self.passengerProgressModel.adbpId;
    NSInteger demandType = self.houseProgressModel ? self.houseProgressRecordInfoModel.demand_type : self.passengerProgressModel.demandType;
    [kNetworkManager requestrProgressBuyerInfoWithAdbpId:adbpId demandType:demandType success:^(SISSBuyerInfoModel *buyerInfoModel) {
        
        self.escrowAccountApplyViewModel.dataArr[1][0].rightStr = buyerInfoModel.buyer_name ? buyerInfoModel.buyer_name : @" ";
        self.escrowAccountApplyViewModel.dataArr[1][1].rightStr = buyerInfoModel.idNo ? buyerInfoModel.idNo : @" ";
        requestCount++;
        if (self.complete) {
            self.complete();
        }
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    self.complete = ^{
        if (requestCount == 2) {
            //在这里 进行请求后的方法，回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        }
    };
}

#pragma mark - 代理
#pragma mark -- UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.escrowAccountApplyViewModel getSectionCount];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.escrowAccountApplyViewModel getRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    NSArray *arr = self.dataArr[indexPath.section];
    return [self.escrowAccountApplyViewModel getCell:tableView indexPath:indexPath];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return [self.escrowAccountApplyViewModel getHeightForHeaderInSection:section];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [self.escrowAccountApplyViewModel getViewHeaderInSection:section];
}

// 取消tableView组头悬停
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

/**
 必选提示
 
 @return 返回YES时需要填写或选择
 */
- (BOOL)requiredTip {

    SISSEscrowAccountInfoModel *escrowAccountInfoModel = [self.escrowAccountApplyViewModel dataArrToEscrowAccountInfoModelWithModel:self.escrowAccountInfoModel];

    if (!escrowAccountInfoModel.amount || escrowAccountInfoModel.amount.length == 0) {
        [SISSTools showSVErrorTitle:@"请输入购房资金" andTime:2 andColor:YES];
        return YES;
    }
    if (!escrowAccountInfoModel.term || escrowAccountInfoModel.term.length == 0) {
        [SISSTools showSVErrorTitle:@"请选择资金划转条件" andTime:2 andColor:YES];
        return YES;
    }
    if (!escrowAccountInfoModel.accountName || escrowAccountInfoModel.accountName == 0) {
        [SISSTools showSVErrorTitle:@"请输入资金账户姓名" andTime:2 andColor:YES];
        return YES;
    }
    if (!escrowAccountInfoModel.accountNum || escrowAccountInfoModel.accountNum == 0) {
        [SISSTools showSVErrorTitle:@"请输入资金账户号码" andTime:2 andColor:YES];
        return YES;
    }
    if (!escrowAccountInfoModel.interestAccountOwner || escrowAccountInfoModel.interestAccountOwner.length == 0) {
        [SISSTools showSVErrorTitle:@"请选择利息账户持有方" andTime:2 andColor:YES];
        return YES;
    }
    if (!escrowAccountInfoModel.interestAccountName || escrowAccountInfoModel.interestAccountName == 0) {
        [SISSTools showSVErrorTitle:@"请输入利息账户姓名" andTime:2 andColor:YES];
        return YES;
    }
    if (!escrowAccountInfoModel.interestAccountNum || escrowAccountInfoModel.interestAccountNum == 0) {
        [SISSTools showSVErrorTitle:@"请输入利息账户号码" andTime:2 andColor:YES];
        return YES;
    }
    if (!escrowAccountInfoModel.month || escrowAccountInfoModel.month == 0) {
        [SISSTools showSVErrorTitle:@"请输入监管月数" andTime:2 andColor:YES];
        return YES;
    }
    self.escrowAccountInfoModel = escrowAccountInfoModel;
    return NO;
}


#pragma mark - 按钮点击事件
#pragma mark -- 保存按钮点击事件
- (void)saveButtonClickAction {
    
    if ([self requiredTip]) return;
    NSString *ahbpId = self.houseProgressModel ? self.houseProgressModel.ahbpId : self.passengerProgressRecordInfoModel.ahbpId;
    NSString *adbpId = self.houseProgressModel ? self.houseProgressRecordInfoModel.adbpId : self.passengerProgressModel.adbpId;
    NSString *ahrId = self.houseProgressModel ? self.houseProgressModel.house.ID : @"";
    NSString *abdId = self.houseProgressModel ? @"" : self.passengerProgressModel.demand.ID;
    if (self.dataSource.count > 0) {
        NSDictionary *parameters = @{
                                     @"id": self.escrowAccountInfoModel.ID,
                                     @"spId": [SISSUserAccount shared].spId,
                                     @"ahbpId": ahbpId,
                                     @"adbpId": adbpId,
                                     @"ahrId": ahrId,
                                     @"abdId": abdId,
                                     @"accountName": self.escrowAccountInfoModel.accountName,
                                     @"accountNum": self.escrowAccountInfoModel.accountNum,
                                     @"amount": self.escrowAccountInfoModel.amount,
                                     @"bank": self.escrowAccountInfoModel.bank,
                                     @"demandType": @(self.houseProgressRecordInfoModel.demand_type),
                                     @"houseType": @(self.houseProgressModel.house.houseresType),
                                     @"interestAccountName": self.escrowAccountInfoModel.interestAccountName,
                                     @"interestAccountNum": self.escrowAccountInfoModel.interestAccountNum,
                                     @"interestAccountOwner": self.escrowAccountInfoModel.interestAccountOwner,
                                     @"month": self.escrowAccountInfoModel.month,
                                     @"term": self.escrowAccountInfoModel.term
                                     };
        [kNetworkManager updateFundSupervisionInfoWithParamters:parameters success:^(id responseObject) {
            if ([responseObject[@"code"] integerValue] == 200) {
                
                SISSEscrowAccountShowViewController *vc = [[SISSEscrowAccountShowViewController alloc] init];
                vc.houseProgressModel = self.houseProgressModel;
                vc.houseProgressRecordInfoModel = self.houseProgressRecordInfoModel;
                vc.passengerProgressModel = self.passengerProgressModel;
                vc.passengerProgressRecordInfoModel = self.passengerProgressRecordInfoModel;
                vc.dataSource = self.escrowAccountApplyViewModel.dataArr;
                [self.navigationController pushViewController:vc animated:YES];
            }
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    } else {
        
        NSDictionary *parameters = @{
                                     @"spId": [SISSUserAccount shared].spId,
                                     @"ahbpId": ahbpId,
                                     @"adbpId": adbpId,
                                     @"ahrId": ahrId,
                                     @"abdId": abdId,
                                     @"accountName": self.escrowAccountInfoModel.accountName,
                                     @"accountNum": self.escrowAccountInfoModel.accountNum,
                                     @"amount": self.escrowAccountInfoModel.amount,
                                     @"bank": self.escrowAccountInfoModel.bank,
                                     @"demandType": @(self.houseProgressRecordInfoModel.demand_type),
                                     @"houseType": @(self.houseProgressModel.house.houseresType),
                                     @"interestAccountName": self.escrowAccountInfoModel.interestAccountName,
                                     @"interestAccountNum": self.escrowAccountInfoModel.interestAccountNum,
                                     @"interestAccountOwner": self.escrowAccountInfoModel.interestAccountOwner,
                                     @"month": self.escrowAccountInfoModel.month,
                                     @"term": self.escrowAccountInfoModel.term
                                     };
        [kNetworkManager insertFundSupervisionInfoWithParamters:parameters success:^(id responseObject) {
            if ([responseObject[@"code"] integerValue] == 200) {
                
                SISSEscrowAccountShowViewController *vc = [[SISSEscrowAccountShowViewController alloc] init];
                vc.houseProgressModel = self.houseProgressModel;
                vc.houseProgressRecordInfoModel = self.houseProgressRecordInfoModel;
                vc.dataSource = self.escrowAccountApplyViewModel.dataArr;
                [self.navigationController pushViewController:vc animated:YES];
            }
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
    
}


#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    self.escrowAccountApplyViewModel = [[SISSEscrowAccountApplyViewModel alloc] init];
    if (self.dataSource.count > 0) {
        self.escrowAccountApplyViewModel.dataArr = self.dataSource.copy;
    }
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] init];
    tableView.estimatedRowHeight = 44;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.escrowAccountApplyViewModel registContractClass:tableView];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    self.escrowAccountApplyViewModel.tableView = tableView;
    
    UIView *footerView = [[UIView alloc ] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 88)];
    
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton setBackgroundColor:MAIN_COLOR];
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    saveButton.layer.cornerRadius = 4;
    saveButton.layer.masksToBounds = YES;
    [footerView addSubview:saveButton];
    self.saveButton = saveButton;
    
    [self.saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(footerView);
        make.width.mas_equalTo(SCREEN_WIDTH * 0.7);
        make.height.mas_equalTo(44);
    }];
    
    self.tableView.tableFooterView = footerView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}

@end
